import os
import datetime
import random
import importlib
import time
from string import ascii_uppercase

from config import settings
from utils.log import logger


def heartbeat(*args, **kwargs):
    """
    程序心跳方法
    :return:
    """
    # logger.info("心跳一下")


def snake_to_hump(string: str):
    """
    snake_to_hump => SnakeToHump
    """
    res = ''
    for s in string.split('_'):
        res += f"{s[0].upper()}{s[1:].lower()}"
    return res


def hump_to_snake(string: str):
    """
    HumpToSnake => hump_to_snake
    """
    res = ''
    for i, s in enumerate(string):
        if i != 0 and s in ascii_uppercase:
            res += f'_{s.lower()}'
        else:
            res += f'{s.lower()}'
    return res


def get_func_ref(func):
    '''
    获取方法的映射路径
    '''
    f"{func.__code__.co_filename}:{func.__name__}"
    path = func.__code__.co_filename.split("schedule_platform")[-1][1:]
    return path.replace('.py', '').replace('/', '.').replace(os.sep, '.') + ":" + func.__name__


def random_ua():
    ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{} Safari/537.36'

    v1 = random.choice([_ for _ in range(105, 108)])
    v2 = random.choice([_ for _ in range(10)])
    v3 = random.choice([_ for _ in range(1000, 9999)])
    v4 = random.choice([_ for _ in range(10, 99)])

    version = f'{v1}.{v2}.{v3}.{v4}'
    return ua.format(version)


def get_function_from_path_string(path_string: str):
    if path_string == settings.undefined:
        return path_string
    module_path, function = path_string.rsplit('.', 1)
    try:
        module = importlib.import_module(module_path)
    except ModuleNotFoundError:
        logger.error(f"[{module_path}]模块没有找到~!")
    else:
        if hasattr(module, function):
            return getattr(module, function)
        else:
            logger.error(f"[{path_string}]方法没有找到~!")

    return None


def retry(times=10):
    def wrap(func):
        def sync_exec(*args, **kwargs):
            exception = None
            for i in range(times + 1):
                try:
                    if i > 0:
                        logger.info(f"{func.__name__}正在进行第{i}次重试")
                    result = func(*args, **kwargs)
                except Exception as e:
                    exception = e
                    time.sleep(1)
                else:
                    return result
            else:
                if exception:
                    logger.error(f"{func.__name__}超出重试次数:{times}")
                    raise exception

        return sync_exec

    return wrap


def format_date(date_str, format_str):
    return datetime.datetime.strptime(date_str, format_str)


if __name__ == '__main__':
    print(hump_to_snake("UserNameModal"))
    print(snake_to_hump("snake_to_hump"))
